package com.guodaxia.gzh.web.user;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
 
public class HmacSHA256Example {
    public static void main(String[] args) {
        // 待加密的数据
        String data = "Hello, world!";
        // 密钥，需要是字节形式
        String key = "mySecretKey";
        
        try {
            // 获取HmacSHA256算法的Mac实例
            Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
            // 初始化Mac实例，设置密钥
            SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
            sha256_HMAC.init(secret_key);
            
            // 执行Mac操作，生成哈希值
            byte[] hash = sha256_HMAC.doFinal(data.getBytes());
            
            // 将哈希值转换为十六进制字符串
            String hexResult = bytesToHex(hash);
            System.out.println("Hex Result: " + hexResult);
            
            // 或者将哈希值转换为Base64字符串
            String base64Result = Base64.getEncoder().encodeToString(hash);
            System.out.println("Base64 Result: " + base64Result);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }
    }
    
    // 辅助方法：将字节数组转换为十六进制字符串
    private static String bytesToHex(byte[] hash) {
        StringBuilder hexString = new StringBuilder(2 * hash.length);
        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if(hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}